//
//  BindingPhoneViewController.m
//  BlackDoPlanet
//
//  Created by Botao on 2018/10/15.
//  Copyright © 2018年 botaoweb. All rights reserved.
//

#import "BindingPhoneViewController.h"
#import "InviteCodeViewController.h"
#import "TabBarViewController.h"
#import "BindingPhoneViewController.h"

@interface BindingPhoneViewController ()<UITextViewDelegate, UIGestureRecognizerDelegate>

{
    NSString *_commonStr;
}
@property(nonatomic, assign)float xWidth;
@property(nonatomic, strong)UIImageView *BGImgeView;
@property(nonatomic, strong)UITextView *phoneNumTV;
@property(nonatomic, strong)UITextView *verifyTV;
@property(nonatomic, strong)UIButton *phoneBtn;
@property(nonatomic, strong)UIButton *verifyBtn;
@property(nonatomic, strong)UIButton *getVerifyBtn;
@property(nonatomic, strong)UIButton *submitBtn;
@property(nonatomic, strong)NSString *phoneNumStr;
@property(nonatomic, strong)NSString *verifyStr;
@property(nonatomic, assign)BOOL isInputPhoneNum;
@property(nonatomic, assign)BOOL isGetVerify;
@property(nonatomic, assign)BOOL isInputVerify;
@property(nonatomic, assign)int timeCount;

@property(nonatomic, strong)NSString *deviceId;

@end

@implementation BindingPhoneViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.xWidth = [Tools theSize:@"width"];
    
    _commonStr = @"";
    self.phoneNumStr = @"";
    self.verifyStr = @"";
    _isInputPhoneNum = NO;
    _isGetVerify = NO;
    _isInputVerify = NO;
    _timeCount = 60;
    
    [self initTopView];
    
    [self initSkipAction];
}

- (void)initSkipAction {
    UIButton *skipBtn = [[UIButton alloc]initWithFrame:CGRectMake(20*_xWidth, [Tools getStatusBarHeight], 50*_xWidth, 40*_xWidth)];
    //skipBtn.backgroundColor = [UIColor cyanColor];
    [skipBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [skipBtn.titleLabel setFont:[UIFont fontWithName:[Tools setFontNamePingFangRegular] size:15*[Tools theSize:@"width"]]];
    [skipBtn setTitle:@"返回" forState:UIControlStateNormal];
    [skipBtn addTarget:self action:@selector(skipLogin) forControlEvents:UIControlEventTouchUpInside];
    [_BGImgeView addSubview:skipBtn];
}

- (void)skipLogin
{
    //NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    //[user setBool:NO forKey:@"sureLogin"];
    [self dismissViewControllerAnimated:YES completion:nil];
    //[[NSNotificationCenter defaultCenter] postNotificationName:@"loginOutSkip" object:nil];
}


- (void)initTopView {
    _BGImgeView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@""]];
    _BGImgeView.backgroundColor = WhiteColor;
    _BGImgeView.frame = self.view.frame;
    _BGImgeView.userInteractionEnabled = YES;
    [self.view addSubview:_BGImgeView];
    
    UIImageView *planet = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@""]];
    planet.frame = CGRectMake(self.view.frame.size.width/2-214/2*_xWidth, [Tools getStatusBarHeight], 214*_xWidth, 193*_xWidth);
    [_BGImgeView addSubview:planet];
    
    _phoneBtn = [[UIButton alloc]initWithFrame:CGRectMake(35*_xWidth, planet.frame.origin.y+planet.frame.size.height+20*_xWidth, self.view.frame.size.width-35*2*_xWidth, 30*_xWidth)];
    [_phoneBtn setTitle:@"输入手机号" forState:UIControlStateNormal];
    [_phoneBtn setTitleColor:LightGrayColor forState:UIControlStateNormal];
    [_phoneBtn.titleLabel setFont:[UIFont fontWithName:[Tools setFontNamePingFangRegular] size:15*[Tools theSize:@"width"]]];
    _phoneBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [_phoneBtn addTarget:self action:@selector(inputPhoneNumAction) forControlEvents:UIControlEventTouchUpInside];
    [_BGImgeView addSubview:_phoneBtn];
    
    UILabel *line1 = [[UILabel alloc]initWithFrame:CGRectMake(_phoneBtn.frame.origin.x, _phoneBtn.frame.origin.y+_phoneBtn.frame.size.height+1, _phoneBtn.frame.size.width, 1)];
    [line1 setBackgroundColor:LightGrayColor];
    [_BGImgeView addSubview:line1];
    
    _getVerifyBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width-(35+15*6)*_xWidth, line1.frame.origin.y+line1.frame.size.height+30*_xWidth, 15*6*_xWidth, 30*_xWidth)];
    [_getVerifyBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [_getVerifyBtn setTitleColor:LightGrayColor forState:UIControlStateNormal];
    [_getVerifyBtn.titleLabel setFont:[UIFont fontWithName:[Tools setFontNamePingFangRegular] size:15*_xWidth]];
    _getVerifyBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [_getVerifyBtn addTarget:self action:@selector(verifyAction) forControlEvents:UIControlEventTouchUpInside];
    [_BGImgeView addSubview:_getVerifyBtn];
    
    UILabel *line2 = [[UILabel alloc]initWithFrame:CGRectMake(_getVerifyBtn.frame.origin.x-1, _getVerifyBtn.frame.origin.y+7*_xWidth, 1, 16*_xWidth)];
    [line2 setBackgroundColor:LightGrayColor];
    [_BGImgeView addSubview:line2];
    
    _verifyBtn = [[UIButton alloc]initWithFrame:CGRectMake(35*_xWidth, _getVerifyBtn.frame.origin.y, line2.frame.origin.x-35*_xWidth, 30*_xWidth)];
    [_verifyBtn setTitle:@"短信验证码" forState:UIControlStateNormal];
    [_verifyBtn setTitleColor:LightGrayColor forState:UIControlStateNormal];
    [_verifyBtn.titleLabel setFont:[UIFont fontWithName:[Tools setFontNamePingFangRegular] size:15*[Tools theSize:@"width"]]];
    _verifyBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [_verifyBtn addTarget:self action:@selector(inputVerifyAction) forControlEvents:UIControlEventTouchUpInside];
    [_BGImgeView addSubview:_verifyBtn];
    
    UILabel *line3 = [[UILabel alloc]initWithFrame:CGRectMake(line1.frame.origin.x, _verifyBtn.frame.origin.y+_verifyBtn.frame.size.height+1, line1.frame.size.width, 1)];
    [line3 setBackgroundColor:LightGrayColor];
    [_BGImgeView addSubview:line3];
    
    _submitBtn = [[UIButton alloc]initWithFrame:CGRectMake(35*_xWidth, line3.frame.origin.y+36*_xWidth, self.view.frame.size.width-35*2*_xWidth, 39*_xWidth)];
    [_submitBtn setBackgroundImage:[UIImage imageNamed:@"button_rectangle"] forState:UIControlStateNormal];
    [_submitBtn setTitleColor:[Tools hexStringToUIColor:@"fdf5ff"] forState:UIControlStateNormal];
    [_submitBtn.titleLabel setFont:[UIFont fontWithName:[Tools setFontNamePingFangRegular] size:17*[Tools theSize:@"width"]]];
    [_submitBtn addTarget:self action:@selector(submitPhone) forControlEvents:UIControlEventTouchUpInside];
    _submitBtn.userInteractionEnabled = NO;
    [_BGImgeView addSubview:_submitBtn];
    [self.submitBtn setTitle:@"立即绑定" forState:UIControlStateNormal];
    
    UILabel *infoLabel = [[UILabel alloc]initWithFrame:CGRectMake(35*_xWidth, _submitBtn.frame.origin.y+80*_xWidth, self.view.frame.size.width-35*2*_xWidth, 39*_xWidth)];
    [infoLabel setFont:[UIFont fontWithName:[Tools setFontNamePingFangRegular] size:17*[Tools theSize:@"width"]]];
    infoLabel.text = @"首次快捷登陆，需绑定手机号";
    infoLabel.textColor = [UIColor whiteColor];
    infoLabel.textAlignment = NSTextAlignmentCenter;
    [_BGImgeView addSubview:infoLabel];
}

- (void)inputPhoneNumAction {
    _phoneNumTV = [[UITextView alloc]initWithFrame:_phoneBtn.frame];
    [_phoneNumTV setFont:[UIFont fontWithName:[Tools setFontNamePingFangRegular] size:15*[Tools theSize:@"width"]]];
    [_phoneNumTV setBackgroundColor:[UIColor whiteColor]];
    _phoneNumTV.textColor = [UIColor blackColor];
    _phoneNumTV.delegate = self;
    _phoneNumTV.keyboardType = UIKeyboardTypeNumberPad;
    [_phoneNumTV becomeFirstResponder];
    [_BGImgeView addSubview:_phoneNumTV];
}

- (void)verifyAction {
    if (_isInputPhoneNum&&(_phoneNumStr.length == 11)) {
        
        if ([_phoneNumStr isEqualToString:@"17711111113"]) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"测试账号无需获取验证码，使用固定验证码6261即可" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确认", nil];
            [alertView show];
            return;
        }
        
        NSLog(@"输入手机号并且格式验证通过，去请求验证码");
        // 60秒倒计时
        __block NSInteger second = 60;
        dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, quene);
        dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
        dispatch_source_set_event_handler(timer, ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                if (second == 0) {
                    self->_getVerifyBtn.userInteractionEnabled = YES;
                    [self->_getVerifyBtn setTitle:[NSString stringWithFormat:@"重新获取"] forState:UIControlStateNormal];
                    second = 60;
                    dispatch_cancel(timer);
                } else {
                    self->_getVerifyBtn.userInteractionEnabled = NO;
                    [self->_getVerifyBtn setTitle:[NSString stringWithFormat:@"%ld秒后重试",(long)second] forState:UIControlStateNormal];
                    second--;
                }
            });
        });
        dispatch_resume(timer);
        _isGetVerify = YES;
        
        [[HttpManager shareInstance] commonRequestWithRequestWay:@"post" url:[RequestUrl theMessageCode] loadStr:@"" param:@{@"phone":_phoneNumStr} Complete:^(NSInteger code, NSDictionary * _Nonnull dictionary) {
            if (code == 0) {
                //获取验证码成功
            }else{
                [Tools showMessage:@"获取验证码失败,请稍后重试"];
            }
        } netCompletBlock:^(NSString * _Nonnull netStr) {
            [Tools showMessage:netStr];
        }];
    }else {
        [Tools showMessage:@"请输入正确的手机号"];
    }
}

- (void)getMessageCode:(NSNotification *)notification
{
    NSLog(@"--- %@",notification.userInfo);
    NSDictionary *resultDict = [[notification userInfo] objectForKey:@"callbackData"];
    NSString *codeString = [NSString stringWithFormat:@"%@",[resultDict objectForKey:@"code"]];
    if ([@"0" isEqualToString:codeString]) {
        //NSDictionary *dict = [resultDict objectForKey:@"body"];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"getMessageCode" object:nil];
}

- (void)inputVerifyAction {
    _verifyTV = [[UITextView alloc]initWithFrame:_verifyBtn.frame];
    [_verifyTV setFont:[UIFont fontWithName:[Tools setFontNamePingFangRegular] size:15*[Tools theSize:@"width"]]];
    [_verifyTV setBackgroundColor:[UIColor whiteColor]];
    _verifyTV.textColor = [UIColor blackColor];
    _verifyTV.delegate = self;
    _verifyTV.keyboardType = UIKeyboardTypeNumberPad;
    
    if (_isGetVerify) {
        [_verifyTV becomeFirstResponder];
        [_BGImgeView addSubview:_verifyTV];
    }else {
        [_verifyTV becomeFirstResponder];
        [_BGImgeView addSubview:_verifyTV];
        //[Tools showMessage:@"请先获取验证码"];
    }
}

//立即绑定
- (void)submitPhone {
    [_phoneNumTV resignFirstResponder];
    [_verifyTV resignFirstResponder];
    
    [self.thirdInfoMutDic setObject:_phoneNumStr forKey:@"phone"];
    [self.thirdInfoMutDic setObject:_verifyStr forKey:@"code"];
    
    [[HttpManager shareInstance] bindingRequestWithUrl:[RequestUrl TheBinding_post] param:self.thirdInfoMutDic Complete:^(NSInteger code, NSDictionary *dictionary)
    {
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        if (code == 0) {
            [user setBool:YES forKey:@"sureLogin"];
            NSMutableDictionary *tempMuDict = [NSMutableDictionary dictionaryWithDictionary:[dictionary objectForKey:@"result"]];
            [tempMuDict setValue:dictionary[@"token"] forKey:@"token"];
            //存用户数据
            [self userInfoCoreData:tempMuDict];
        }else{
            [user setBool:NO forKey:@"sureLogin"];
            [Tools showMessage:[dictionary objectForKey:@"msg"]];
        }
    }];
}

//存用户数据
- (void)userInfoCoreData:(NSDictionary *)dic
{
    NSString *source = [NSString stringWithFormat:@"%@",[dic objectForKey:@"source"]];
    NSString *userId = [NSString stringWithFormat:@"%@",[dic objectForKey:@"uuid"]];
    NSString *phone = [NSString stringWithFormat:@"%@",[dic objectForKey:@"phone"]];
    NSString *areaNum = [NSString stringWithFormat:@"%@",[dic objectForKey:@"areaNum"]];
    NSString *areaName = [NSString stringWithFormat:@"%@",[dic objectForKey:@"areaName"]];
    NSString *blackDrill = [NSString stringWithFormat:@"%@",[dic objectForKey:@"blackDrill"]];
    NSString *unBlackDrill = [NSString stringWithFormat:@"%@",[dic objectForKey:@"unBlackDrill"]];
    NSString *stamina = [NSString stringWithFormat:@"%@",[dic objectForKey:@"stamina"]];
    NSString *invitCode = [NSString stringWithFormat:@"%@",[dic objectForKey:@"invitCode"]];
    NSString *availability = [NSString stringWithFormat:@"%@",[dic objectForKey:@"availability"]];
    NSString *token = [NSString stringWithFormat:@"%@",[dic objectForKey:@"token"]];
    NSDictionary *userInfoDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                 userId, @"userId",
                                 phone, @"phone",
                                 areaNum, @"areaNum",
                                 areaName, @"areaName",
                                 blackDrill, @"blackDrill",
                                 unBlackDrill, @"unBlackDrill",
                                 stamina, @"stamina",
                                 invitCode, @"invitCode",
                                 availability, @"availability",
                                 source, @"source",
                                 @"1", @"isLogin",
                                 token, @"token",
                                 nil];
    UserModel *userModel = [[UserModel alloc]initWithDicForUserInfo:userInfoDic];
    [Dao login:userModel];
    
    if ([@"1" isEqualToString:source]) {
        // 邀请码VC
        InviteCodeViewController *inviteCodeVC = [[InviteCodeViewController alloc]init];
        [self presentViewController:inviteCodeVC animated:YES completion:nil];
    }else {
        [self dismissViewControllerAnimated:YES completion:nil];
        self.view.window.rootViewController = [[TabBarViewController alloc] init];
    }
}


#pragma mark TextView Delegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if (textView == _phoneNumTV) {
        if ((text.length == 0)&&(textView.text.length>0)) {
            _phoneNumStr = [NSString stringWithFormat:@"%@%@", [textView.text substringToIndex:textView.text.length-1], text];
        }else {
            _phoneNumStr = [NSString stringWithFormat:@"%@%@", textView.text, text];
        }
        if ([@"" isEqualToString:_phoneNumStr]) {
            _isInputPhoneNum = NO;
        }else {
            _isInputPhoneNum = YES;
        }
        
    }else if (textView == _verifyTV) {
        if ((text.length == 0)&&(textView.text.length>0)) {
            _verifyStr = [NSString stringWithFormat:@"%@%@", [textView.text substringToIndex:textView.text.length-1], text];
        }else {
            _verifyStr = [NSString stringWithFormat:@"%@%@", textView.text, text];
        }
        if ([@"" isEqualToString:_verifyStr]) {
            _isInputVerify = NO;
            [_submitBtn setBackgroundImage:[UIImage imageNamed:@"button_rectangle"] forState:UIControlStateNormal];
            _submitBtn.userInteractionEnabled = NO;
        }else {
            _isInputVerify = YES;
            [_submitBtn setBackgroundImage:[UIImage imageNamed:@"button_rectangle"] forState:UIControlStateNormal];
            _submitBtn.userInteractionEnabled = YES;
        }
    }
    return YES;
}

#pragma mark 设置手势
-(void)setGesture{
    UITapGestureRecognizer *recognierUp = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(resignFirstResponder:)];
    [recognierUp setDelegate:self];
    [_BGImgeView addGestureRecognizer:recognierUp];
}
-(IBAction)resignFirstResponder:(id)sender{
    NSLog(@"_phoneNumStr: %@", _phoneNumStr);
    NSLog(@"_verifyStr: %@", _verifyStr);
    if (!_isInputPhoneNum) {
        [_phoneNumTV setHidden:YES];
    }
    if (!_isInputVerify) {
        [_verifyTV setHidden:YES];
    }
    [_phoneNumTV resignFirstResponder];
    [_verifyTV resignFirstResponder];
}


@end
